package com.lagou.initializer;

import com.lagou.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) {
        System.out.println("通过注解的方式初始化Spring的上下文......");
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        // 注册spring的配置类（替代传统项目中xml的configuration）
        ac.register(AppConfig.class);
        ac.refresh();
        System.out.println("基于java代码的方式初始化DispatcherServlet......");
        DispatcherServlet servlet = new DispatcherServlet(ac);
        // 添加servlet (还可以 addFilter 或 addListener)
        ServletRegistration.Dynamic app = servletContext.addServlet("app", servlet);
        app.setLoadOnStartup(1);
        app.addMapping("/app/*");
    }
}
